package com.ksyun.camp.controller;

import com.ksyun.camp.client.FeinClient;
import com.ksyun.camp.modle.dto.PayDto;
import com.ksyun.camp.modle.dto.TransferDto;
import com.ksyun.camp.modle.vo.AccountVo;
import com.ksyun.camp.modle.vo.AuthResponse;
import com.ksyun.camp.modle.vo.Result;
import com.ksyun.camp.service.OnePassService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping
public class OnePassController {

    @Autowired
    private OnePassService onePassService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping(value = "/onePass/batchPay")
    public Result batchPay(@RequestHeader("X-KSY-REQUEST-ID") String requestId,
                           @RequestBody PayDto payDto) {
        boolean isRepeat = checkRequestId(requestId);
        if (isRepeat) {
            return Result.build(null, AuthResponse.REQUESTID_REPEAT, requestId);
        }

        return onePassService.batchPay(payDto, requestId);
    }

    @PostMapping(value = "/onePass/userTrade")
    public Result userTrade(@RequestHeader("X-KSY-REQUEST-ID") String requestId,
                            @RequestBody TransferDto transferDto) {
        boolean isRepeat = checkRequestId(requestId);
        if (isRepeat) {
            return Result.build(null, AuthResponse.REQUESTID_REPEAT, requestId);
        }
        log.info("用户{}向用户{}转账", transferDto.getSourceUid(), transferDto.getTargetUid());
        return onePassService.userTrade(transferDto, requestId);
    }

    @PostMapping(value = "/onePass/queryUserAmount")
    public Result<List<AccountVo>> getUserAmount(
            @RequestHeader("X-KSY-REQUEST-ID") String requestId,
            @RequestBody List<Long> uids) {
        boolean isRepeat = checkRequestId(requestId);
        if (isRepeat) {
            return Result.build(null, AuthResponse.REQUESTID_REPEAT, requestId);
        }

        return onePassService.getUserAmount(uids, requestId);
    }

    private boolean checkRequestId(String requestId){
        String requestNum = redisTemplate.opsForValue().get("requestId:" + requestId);
        if(requestNum == null){
            redisTemplate.opsForValue().set("requestId:" + requestId, String.valueOf(0), 60, TimeUnit.SECONDS);
            return false;
        }
        redisTemplate.opsForValue().increment("requestId:" + requestId, 1L);
        return true;
    }

}
